package AdminService

import (
	"context"
	"gdshop-admin-go-api/library/tools"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"strings"
	"time"
)

// GetPermsByAdminId 按 adminid 获取角色及角色下的权限
func GetPermsByAdminId(ctx context.Context, adminId int) ([]string, error) {
	dbPrefix := g.Cfg().GetString("database.prefix")
	cacheDuration := g.Cfg().GetDuration("site.AdminCacheTimeout") * time.Second
	// 取出 权限
	var permsRes []gdb.Value
	permsRes, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "sys_menu").As("sm").LeftJoin("sys_role_menu srm",
		"srm.menu_id = sm.id").Where(
		"sm.type = 2 AND srm.role_id IN (SELECT role_id FROM "+dbPrefix+"admin_role WHERE admin_id = ?)",
		adminId).Fields("sm.perms").Cache(cacheDuration,
		"adminCache:perms:"+gconv.String(adminId),
	).Array()
	if err != nil {
		return nil, err
	}
	// 整理权限列表
	permsTmp := gconv.SliceStr(permsRes)
	var perms []string
	for _, item := range permsTmp {
		if strings.Index(item, ",") > -1 {
			perms = append(perms, strings.Split(item, ",")...)
		} else {
			perms = append(perms, item)
		}
	}

	return tools.RemoveDuplicatesAndEmpty(perms), nil
}
